package service

import (
	"server/internal/model"

	"github.com/jinzhu/gorm"
)

func (svc *Service) GetUserInfo(username string) (map[string]interface{}, error) {
	u := &model.UserInfo{
		Username: username,
	}

	userInfo, err := u.Get(svc.engine)
	if err == gorm.ErrRecordNotFound {
		err = u.Create(svc.engine)
		if err != nil {
			return nil, err
		}
		userInfo, err = u.Get(svc.engine)
	}

	if err != nil {
		return nil, err
	}

	info := make(map[string]interface{})
	info["username"] = userInfo.Username
	info["schoolId"] = userInfo.SchoolId
	info["name"] = userInfo.Name
	info["isMale"] = userInfo.IsMale
	info["phoneNumber"] = userInfo.PhoneNumber

	return info, nil
}

func (svc *Service) SetUserInfo(username, schoolId, name, phoneNumber string, isMale int) error {
	u := &model.UserInfo{
		Username: username,
	}

	values := make(map[string]interface{})
	values["school_id"] = schoolId
	values["name"] = name
	values["is_male"] = isMale
	values["phone_number"] = phoneNumber

	return u.Update(svc.engine, values)
}
